package com.orhon.smartcampus.modules.material.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.material.dao.BuildingsDao;
import com.orhon.smartcampus.modules.material.dao.UnitDao;
import com.orhon.smartcampus.modules.material.entity.Buildings;
import com.orhon.smartcampus.modules.material.entity.Unit;
import com.orhon.smartcampus.modules.material.gqlInputModel.GQLUnitInput;
import com.orhon.smartcampus.modules.material.inputMapper.UnitInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddUnitMutation implements DataFetcher {



    @Autowired
    UnitDao unitDao;

    @Autowired
    BuildingsDao buildingsDao;

    @Autowired
    SchoolsDao schoolsDao;

    @Autowired
    TokenService tokenService;

    /**
     * 单元管理
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
        String token = tokenService.getSystemToken();
        Long schoolId = JwtUtils.getSchoolId(token);

        GQLUnitInput input = UnitInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Unit unit = null;

        if (input.getId() != null) {
            unit = unitDao.get(Unit.class, input.getId());
            unit.setUpdatedAt(new Date());
        }
        else{
            unit = new Unit();
            unit.setCreatedAt(new Date());
        }

        if(input.getBuilding_id() != null) {
            unit.setMaterialBuildingsByBuildingsId( buildingsDao.get(Buildings.class, input.getBuilding_id()));
        }
        if(input.getCode() != null){

            unit.setUnitCode(input.getCode());
        }
        if(input.getTel() != null){

            unit.setUnitTel(input.getTel());
        }
        if(input.getFloor_num() != null){

            unit.setFloorNum(input.getFloor_num());
        }
        if(schoolId != null) {
            unit.setBaseSchoolsBySchoolId( schoolsDao.get(Schools.class, schoolId));
        }
        if(input.getManager() != null){

            unit.setUnitManager(JSON.toJSONString(input.getManager()));
        }
        if(input.getName() != null){

            unit.setUnitName(JSON.toJSONString(input.getName()));
        }
        try{
            unitDao.saveOrUpdate(unit);
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }
        return Result.ok();
    }
}

